package com.longrise.android.byjk.plugins.vip.myintegral;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.common.base.BaseFragment;
import com.longrise.android.byjk.common.UrlConstants;
import com.longrise.android.byjk.event.MyIntegralEvent;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.utils.PrintLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Created by callxkj on 2017/4/17.
 * 我的积分
 */

public class MyIntegralFragment extends BaseFragment implements BaseQuickAdapter.RequestLoadMoreListener {
    public static final String PAGE = "page";
    public static final String PAGE_ALL = "page_all";
    public static final String PAGE_EXPEND = "page_expend";
    public static final String PAGE_INCOME = "page_income";
    private static final String TAG = "MyIntegralFragment";
    private RecyclerView mRcv;
    private MyIntegralRcvAdapter mAdapter;
    private String mCurrentPage;
    private boolean mIsVisibleToUser = false;
    private boolean mViewCreated = false;
    private boolean isFirstLoaded = false; //页面第一次有没有重新加载过数据
    private int mPageNum;
    private int mSinglepageNum = 10;  //单次请求获取的item数量
    private int mCurrentBeansLen;

    @Override
    protected int getLayoutResourse(@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_myintegral_frg;
    }

    @Override
    public void initView() {
        mViewCreated = true;
        mRcv = (RecyclerView) mRootView.findViewById(R.id.item_rcv_myintegral_frg_rcv);
        getIntentData();
        initAdapter();
        if (mIsVisibleToUser) {
            getFirstData(1, false);
        }
        EventBus.getDefault().register(this);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        mIsVisibleToUser = isVisibleToUser;
        if (mViewCreated && mIsVisibleToUser) {
            getFirstData(1, false);
        }
    }

    private void initAdapter() {
        mRcv.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapter = new MyIntegralRcvAdapter(mCurrentPage);
        mAdapter.setOnLoadMoreListener(this);
        mRcv.setAdapter(mAdapter);
    }

    private void getIntentData() {
        mCurrentPage = getArguments().getString(PAGE);
    }

    private void getFirstData(int pageNum, boolean isLoadmore) {
        if (!isFirstLoaded) {
            getData(pageNum, isLoadmore);
            isFirstLoaded = true;
        }
    }

    private void getData(int pageNum, final boolean isLoadmore) {
        String serverName = null;
        mPageNum = pageNum;
        switch (mCurrentPage) {
            case PAGE_ALL: //全部
                serverName = "bbt_vip_sTotalScores";
                break;
            case PAGE_EXPEND: //支出
                serverName = "bbt_vip_sTotalCostScores";
                break;
            case PAGE_INCOME: //收入
                serverName = "bbt_vip_sTotalGetScores";
                break;
        }
        if (TextUtils.isEmpty(serverName)) {
            return;
        }
        EntityBean bean = new EntityBean();
        bean.set("userid", UserInfor.getInstance().getUserid());
        bean.set("cardno", UserInfor.getInstance().getUsersfzh());
        bean.set("pageSize", mSinglepageNum);
        bean.set("pageNum", pageNum);
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        LoadDataManager.getInstance().callService(null, UrlConstants.BaseUrl,
                serverName, fbean, new LoadDataManager.OnRequestCallListener() {

                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        try {
                            EntityBean bean = (EntityBean) result;
                            parseBeans(bean, isLoadmore);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFinished(String key, String service) {

                    }

                    @Override
                    public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                        if (isLoadmore) {
                            mAdapter.loadMoreFail();
                        }
                    }
                });
    }

    private void parseBeans(EntityBean bean, boolean isLoadmore) {
        Integer resultstate = bean.getInt("resultstate");
        String resultdesc = bean.getString("resultdesc");
        if (resultstate == 1) {
            EntityBean[] resultBeans = bean.getBeans("result");
            if (resultBeans == null) {
                mCurrentBeansLen = 0;
                resultBeans = new EntityBean[]{};
            } else {
                mCurrentBeansLen = resultBeans.length;
            }
            mAdapter.setDatas(resultBeans, isLoadmore);
            if (isLoadmore) {
                mAdapter.loadMoreComplete();
            }
            if (mCurrentBeansLen < mSinglepageNum) {
                mAdapter.loadMoreEnd();
            }
        } else {
            mCurrentBeansLen = 0;
            showToast(resultdesc);
            if (isLoadmore) {
                mAdapter.loadMoreFail();
            }
        }
    }

    @Override
    public void onLoadMoreRequested() {
        PrintLog.e(TAG, "onLoadMoreRequested");
//        if (mAdapter.getData().size() < 8) {
//            mAdapter.loadMoreEnd(true);
//        } else {
        if (mCurrentBeansLen < mSinglepageNum) {
            //mAdapter.loadMoreEnd(false);
        } else {
            getData(mPageNum + 1, true);
        }
//        }


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMyIntegralEvent(MyIntegralEvent event){
        if(event.ismIsNeedRefresh()){
            getData(1, false);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
